/**
 * 简化版流式请求工具
 * 基于x-request和x-stream实现
 */

import { getToken } from '@/utils/auth';
import { globalMessage } from './globalMessage';

/**
 * 默认流分隔符
 */
const DEFAULT_STREAM_SEPARATOR = '\n\n';

/**
 * 默认部分分隔符
 */
const DEFAULT_PART_SEPARATOR = '\n';

/**
 * 默认键值分隔符
 */
const DEFAULT_KV_SEPARATOR = ':';

/**
 * 检查字符串是否有效
 */
const isValidString = (str: string) => (str ?? '').trim() !== '';

/**
 * 分割流数据
 */
function splitStream() {
  let buffer = '';

  return new TransformStream<string, string>({
    transform(streamChunk, controller) {
      buffer += streamChunk;
      const parts = buffer.split(DEFAULT_STREAM_SEPARATOR);
      
      parts.slice(0, -1).forEach((part) => {
        if (isValidString(part)) {
          controller.enqueue(part);
        }
      });
      
      buffer = parts[parts.length - 1];
    },
    flush(controller) {
      if (isValidString(buffer)) {
        controller.enqueue(buffer);
      }
    },
  });
}

/**
 * 分割部分数据
 */
function splitPart() {
  return new TransformStream<string, Record<string, any>>({
    transform(partChunk, controller) {
      const lines = partChunk.split(DEFAULT_PART_SEPARATOR);
      
      const output = lines.reduce<Record<string, any>>((acc, line) => {
        const separatorIndex = line.indexOf(DEFAULT_KV_SEPARATOR);
        
        if (separatorIndex === -1) return acc;
        
        const key = line.slice(0, separatorIndex);
        if (!isValidString(key)) return acc;
        
        const value = line.slice(separatorIndex + 1);
        return { ...acc, [key]: value };
      }, {});
      
      if (Object.keys(output).length === 0) return;
      controller.enqueue(output);
    },
  });
}

/**
 * 处理流式数据
 */
function createStream(readableStream: ReadableStream<Uint8Array>) {
  if (!(readableStream instanceof ReadableStream)) {
    throw new Error('参数必须是ReadableStream实例');
  }
  const decoderStream = new TextDecoderStream();
  
  const stream = readableStream
    .pipeThrough(decoderStream)
    .pipeThrough(splitStream())
    .pipeThrough(splitPart());
  
  // 支持异步迭代器
  (stream as any)[Symbol.asyncIterator] = async function* () {
    const reader = this.getReader();
    
    while (true) {
      const { done, value } = await reader.read();
      
      if (done) break;
      if (!value) continue;
      yield JSON.parse(value.data);
    }
  };
  
  return stream as ReadableStream<Record<string, any>> & AsyncGenerator<Record<string, any>>;
}

/**
 * 简化版流式请求方法
 * @param url 请求URL
 * @param options 请求选项
 * @returns 支持for await的流
 */
export async function streamRequest(url: string, options: RequestInit = {}) {
  const { headers = {}, ...rest } = options;
  
  // 添加授权Token
  const token = getToken();
  const authHeaders: Record<string, string> = {};
  if (token) {
    authHeaders['Authorization'] = `Bearer ${token}`;
  }
  
  if(!url.includes('http')){
    url = (import.meta.env.VITE_API_BASE_URL || 'http://localhost:20080/' ) + url;
  }
  
  const response = await fetch(url, {
    headers: {
      'Content-Type': 'application/json',
      ...authHeaders,
      ...headers,
    },
    ...rest,
  });
  
  if (!response.ok) {
    const errorMsg = `请求失败: ${response.status} ${response.statusText}`;
    globalMessage.error(errorMsg);
    throw new Error(errorMsg);
  }
  
  const contentType = response.headers.get('content-type') || '';
  const mimeType = contentType.split(';')[0].trim();
  
  if (mimeType === 'application/json') {
    const jsonData = await response.json();
    // 检查返回的JSON是否包含错误信息
    if (jsonData && jsonData.success === false) {
      const errorMsg = jsonData.message || '请求失败';
      globalMessage.error(errorMsg);
      throw new Error(errorMsg);
    }
    return jsonData;
  }
  
  if (mimeType === 'text/event-stream') {
    return createStream(response.body!);
  }
  
  throw new Error(`不支持的响应类型: ${contentType}`);
}

export default streamRequest; 